#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

/*
gcc -D MAC_OS_X -framework GDAL -I/usr/local/lib/erlang/lib/erl_interface-3.5.9/include/ -L/usr/local/lib/erlang/lib/erl_interface-3.5.9/lib/ complex.c test.c -lerl_interface -lei

*/
#ifdef MAC_OS_X
    #include <GDAL/gdal.h>
    #include <GDAL/cpl_string.h>
#else
    #include "gdal.h"
    #include "cpl_string.h"
#endif

#include "erl_interface.h"
#include "ei.h"

#include "ai_image.h"
extern int spectrometer(byte* data, int size, band *pBand1, band *pBand2, band *pBand3);

#define IMG_SIZE 1048576

GDALDatasetH createMeomroyDataset(int nBands, int nXSize, int nYSize) {
    GDALDriverH memDriver = GDALGetDriverByName("MEM");

    const char *pszDstFilename = "mem_filename_";
    GDALDatasetH memDS = GDALCreate(memDriver, pszDstFilename, 
                nXSize, nYSize, nBands, GDT_Byte, 
                NULL);  // There are no supported creation options.
    return memDS;
}

void copyToMemory(GDALDatasetH memDS, GByte *bandData, int nthBands, int nXSize, int nYSize) {
    GDALRasterBandH dstBand = GDALGetRasterBand(memDS, nthBands);
    GDALRasterIO(dstBand, GF_Write, 
                0, 0, nXSize, nYSize, bandData, 
                nXSize, nYSize, GDT_Byte, 
                0, 0);
}

int length(GByte * data) {
    int len = 0;
    for(; *data != '\0'; ++data) {
        ++len;
    }
    return len;
}

int main() {
    erl_init(NULL, 0);
    GDALAllRegister();
    
    FILE *fp = fopen("01.jpg", "r");
    byte data[IMG_SIZE];
    fread(data, IMG_SIZE, 1, fp);
    fclose(fp);

    int nXSize, nYSize;
    band band1;
    band band2, band3;
    int band1_size = spectrometer(data, IMG_SIZE, &band1, &band2, &band3);
    printf("band1: size: %d, xsize: %d, ysize: %d\n", band1_size, band1.xSize, band1.ySize);
    printf("band2->xSize: %d, band2->ySize: %d, \n", band2.xSize, band2.ySize);

    GDALDatasetH hDS = createMeomroyDataset(1, band3.xSize, band3.ySize);
    copyToMemory(hDS, band3.data, 1, band3.xSize, band3.ySize);

    GDALDriverH hDriver = GDALGetDriverByName( "PNG" );
    GDALDatasetH hOutDS = GDALCreateCopy( hDriver, "./out8.png", hDS, TRUE, NULL, NULL, NULL );
    GDALClose(hOutDS);

    ETERM* res_data = erl_mk_binary(band1.data, band1_size);
//    erl_encode(res_data, buf);
    printf("data len: %d\n", erl_term_len(res_data));
    printf("sizeof(int) = %d\n", sizeof(int));
    printf("sizeof(unsigned long) = %d\n", sizeof(unsigned long));
}
